package com.binhanh.sql.dao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.binhanh.sql.bo.Video;
import com.binhanh.sql.hibernate.HibernateUtil;

public class VideoDAO {

	/**
	 * insert danh sách video vào database
	 * @param lst
	 * @return
	 */
	public boolean insert(ArrayList<Video> lst) {
		boolean ret = false;
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			int id;
			for (Video video : lst) {
				id = (Integer) session.save(video);
				video.setId(id);
			}
			tx.commit();
			ret = true;
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return ret;
	}

	/* Method to READ all the Videos */
	public void listVideos() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			List Videos = session.createQuery("FROM Video").list();
			for (Iterator iterator = Videos.iterator(); iterator.hasNext();) {
				Video Video = (Video) iterator.next();
				System.out.print("First Name: " + Video.getTitle());
			}
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	/* Method to UPDATE salary for an Video */
	public void updateVideo(Video video) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.update(video);
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	/* Method to DELETE an Video from the records */
	public void deleteVideo(Integer VideoID) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Video Video = (Video) session.get(Video.class,
					VideoID);
			session.delete(Video);
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}
}
